package com.tfswx.jkgl.core.utils;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;

/**
 * @author ricky
 * @date 2021/12/17
 */
public class UrlUtil {
    private static final int PORT;

    static {
        ServerConfig bean = SpringUtil.getBean(ServerConfig.class);
        PORT = bean.getPort();
    }

    private UrlUtil() {
    }

    public static HttpServletRequest getRequest() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public static HttpHeaders getHeaders() {
        HttpHeaders headers = new HttpHeaders();
        HttpServletRequest request = getRequest();
        if (request != null) {
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String s = headerNames.nextElement();
                headers.put(s, Collections.singletonList(request.getHeader(s)));
            }
        }
        return headers;
    }

    public static String getUrl(String oldUrl) {
        String url = oldUrl;
        if (oldUrl.startsWith("http")) {
            return url;
        }
        HttpServletRequest request = getRequest();
        String baseUrl = "";
        if (request != null) {
            baseUrl = request.getScheme() + "://127.0.0.1:" + PORT;
        }
        url = baseUrl + oldUrl;
        return url;
    }
}
